//
//  MILSettingViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/15.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILSettingViewController.h"
#import "MILMyCoderViewController.h"
#import "MILFeedBackViewController.h"
#import "MILProductUseGuideViewController.h"
#import "modifyUserInformation.h"
#import "GetUserInfoApi.h"

@interface MILSettingViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIButton *nickNameBtn;
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;
@property(nonatomic,strong)NSMutableArray *myDataArray;
@property(nonatomic,assign)BOOL isCamera;
@end

@implementation MILSettingViewController
#pragma mark -- 懒加载
- (NSMutableArray *)myDataArray
{
    if (!_myDataArray)
    {
        _myDataArray = [NSMutableArray array];
        NSArray *arr = @[@[@{@"title":@"产品使用指南",@"image":@"productUse"},
                           @{@"title":@"意见反馈",@"image":@"feedBack"}],
                         @[@{@"title":@"退出",@"image":@"exit"}]];
        [_myDataArray addObjectsFromArray:arr];
    }
    
    return _myDataArray;
}

#pragma mark -- UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILSettingView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//初始化UI
- (void)initMILSettingView
{
    self.iconBtn.layer.cornerRadius = 48.5;
    self.iconBtn.clipsToBounds = YES;
    //获取用户资料
    [self getUserInfo];
}


- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"设置"];
    self.navigationBar.backgroundColor = [UIColor blackColor];
    [self setLeftButtonImage:[UIImage imageNamed:@"h"]];
    
}

//获取用户资料
- (void)getUserInfo
{
    //获取用户个人信息
    GetUserInfoApi *infoApi = [[GetUserInfoApi alloc]initWithDic:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN)}];
    [infoApi startWithCompletionAnimation:NO andBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *dic = [infoApi responseJSONObject];
        if([dic[@"errcode"] intValue] == 0) {
            NSDictionary * data = dic[@"data"];
            NSLog(@"[获取到用户信息data = %@]",data);
            if (![data[@"image"]isEqualToString:@""]) {
                [self.iconBtn sd_setImageWithURL:[NSURL URLWithString:data[@"image"]] forState:UIControlStateNormal];
                SAVE_OBJECT(data[@"image"], ICON);
            }
            else
            {
                [self.iconBtn setImage:[UIImage imageNamed:@"touxiang"] forState:UIControlStateNormal];
            }
            if (data[@"nickname"]) {
                [self.nickNameBtn setTitle:data[@"nickname"] forState:UIControlStateNormal];
                SAVE_OBJECT(data[@"nickname"], NICKNAME);
                [self.nickNameBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
            }
            SAVE_OBJECT(data[@"sex"], SEX);
        } else {
            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        }
    } backfailure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];

    } requestFailure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];

    }];
    
//    [infoApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
//       
//       
//    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
//    }];
}

#pragma mark -- 按钮点击
//修改头像
- (IBAction)modifyUserIconAction:(UIButton *)sender {
    //设置头像
    [self setUserIcon];
}

//跳转二维码界面
- (IBAction)gotoUserCoderVCAction:(UIButton *)sender {
    MILMyCoderViewController *milMyCoderVC = [[MILMyCoderViewController alloc]init];
    [self.navigationController pushViewController:milMyCoderVC animated:YES];
}

//修改昵称
- (IBAction)modifyNickNameAction:(UIButton *)sender {
    //修改昵称
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入昵称" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *nickFeild = [alert textFieldAtIndex:0];
    nickFeild.font = [UIFont systemFontOfSize:11];
    nickFeild.placeholder = @"请在此处输入昵称";
    alert.tag = 200;
    [alert show];
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.myDataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *myArray = self.myDataArray[section];
    return myArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell  *Cell=[tableView  dequeueReusableCellWithIdentifier:@"Cell"];
    if (!Cell)
    {
        Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    if (indexPath.section == 0)
    {
        Cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSArray *myArray = self.myDataArray[indexPath.section];
    NSDictionary *dic = myArray[indexPath.row];
    Cell.textLabel.text = dic[@"title"];
    Cell.imageView.image = [UIImage imageNamed:dic[@"image"]];
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.section)
    {
        case 0:
        {
            switch (indexPath.row)
            {
                case 0:
                {
                    //产品指南
                    MILProductUseGuideViewController *milProductUseGuideVC = [[MILProductUseGuideViewController alloc]init];
                    [self.navigationController pushViewController:milProductUseGuideVC animated:YES];
                }
                    break;
                case 1:
                {
                    //意见反馈
                    MILFeedBackViewController *milFeedBackVC = [[MILFeedBackViewController alloc]init];
                    [self.navigationController pushViewController:milFeedBackVC animated:YES];
                    
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            [[AlertViewManager shareManager]initWithMessage:@"是否退出账号？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
                if (buttonIndex == 1) {
                    //退出
                    REMOVE_OBJECT(PASSWORD);
                    SAVE_OBJECT(@"NO", LOGIN);   // 登录状态保存来设置根控制器
                    [[AppDelegate defaultService]setRootViewController];
                }
            }];

        }
            break;
            
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return   15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 1;
}

#pragma mark  --设置头像事件
//设置头像事件
-(void)setUserIcon
{
    UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:@"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍摄照片",@"相册", nil] ;
    [sheet showInView:self.view];}

#pragma mark - 选相片代理
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 导入图片 or 拍照
    if(buttonIndex == 0)
    {
        //        [self goToImagePicker:YES];
        [self formcamera];
        
    }
    else if(buttonIndex == 1){
        //        [self goToImagePicker:NO];
        [self formphoto];
        
    }
}

-(void)formcamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.isCamera=YES;
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing=YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
}
-(void)formphoto
{
    self.isCamera=NO;
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
    NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
    [[NSFileManager defaultManager]removeItemAtPath:PicPath(UID) error:nil];
    
    if (imageData.length > 100 * 1024) {
        if (imageData.length > 1000 * 1024) {
            [UIImageJPEGRepresentation(image, 0.2f) writeToFile:PorPath atomically:YES];
        } else {
            [UIImageJPEGRepresentation(image, 0.4f) writeToFile:PorPath atomically:YES];
        }
    } else {
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
    modifyUserInformation *modifyApi = [[modifyUserInformation alloc]initWithDic:@{@"image":PorPath}];
    [modifyApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        NSDictionary *dic = [modifyApi responseJSONObject];
        NSLog(@"errcode dic = %@",dic[@"errmsg"]);
        if([dic[@"errcode"] intValue] == 0) {
            [SVProgressHUD showSuccessWithStatus:@"修改头像成功"];
            [self getUserInfo];
        } else {
            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        }
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}


#pragma mark  alertView修改昵称事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1)
    {
        switch (alertView.tag)
        {
            case 200:
            {
                //此处向服务器提交修改昵称的请求
                
                UITextField *nickTextField = [alertView textFieldAtIndex:0];
                [nickTextField endEditing:YES];
                if (nickTextField.text.length == 0) {
                    [SVProgressHUD showErrorWithStatus:@"名字不能为空"];
                    return;
                }
                
                if (nickTextField.text.length>20) {
                    [SVProgressHUD showErrorWithStatus:@"名字长度不能超过20个"];
                    return;
                }
                
                if ([NSString isContainsTwoEmoji:nickTextField.text ]) {
                    [SVProgressHUD showErrorWithStatus:@"名字不能使用表情"];
                    return;
                }
                
                modifyUserInformation *modifyApi = [[modifyUserInformation alloc]initWithDic:@{@"nickname":nickTextField.text}];
                [modifyApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                    NSDictionary *dic = [modifyApi responseJSONObject];
                    NSLog(@"errcode dic = %@",dic[@"errmsg"]);
                    if([dic[@"errcode"] intValue] == 0) {
                        [SVProgressHUD showSuccessWithStatus:@"修改昵称成功"];
                        [self getUserInfo];
                    } else {
                        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                    }
                    
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                    [SVProgressHUD showErrorWithStatus:@"请求失败"];
                }];
                
            }
                break;
        default:
                break;
        }
        
    }
    
}



@end
